#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: v1_api_base.py 
@version:
@time: 2021/12/30 
"""
from time import sleep

import requests

from TapClientCore.T01_init_conf.v1_init.init_config import requests_retime
from TapUtil.logfunc.logger import logger
from TapClientCore.T02_tm_api.api_util.util_func import *
from TapClientCore.T01_init_conf.v1_init.init_config import config
from TapClientCore.T02_tm_api.api_base_path import *
from TapException.TM import *


class V1ApiBase:
    # for requests
    get = 'GET'
    post = 'POST'
    patch = 'PATCH'
    delete = 'DELETE'
    serve = session = cookies = access_token = ws_uri = Xtoken = None
    # for tapdata
    server, setting, user_id, tapdata_product, _api = None, None, None, None, None
    # for this
    ERROR = False
    ...

    def __init__(self, change=''):
        if change:
            config.update(change)
        self.setting = config
        self.serve = self.setting['serve']
        # url
        self.url()
        # auth
        if self.session is None:
            self.session = requests.session()
        if self.serve in ["http://test.cloud.tapdata.net"]:
            self._api = api_joint(TM, API)  # 云版需要增加tm/路径
            if self.ERROR is False:
                if self.Xtoken is None:
                    self.dfs_login()
                    self.dfs_ws()
            self.tapdata_product = "dfs"
        elif self.serve in "https://cloud.tapdata.net":
            self._api = api_joint(TM, API)  # 云版需要增加tm/路径
            if self.ERROR is False:
                if self.Xtoken is None:
                    self.production_dfs_login()
                    self.production_dfs_ws()
            self.tapdata_product = "dfs"
        else:
            self._api = API
            self.user = self.setting['user']
            if self.cookies is None:
                self.daas_login()
            if self.ERROR is False:
                self.daas_ws()
            self.tapdata_product = "daas"

    def url(self):
        if self.serve in ["http://test.cloud.tapdata.net",
                          "https://cloud.tapdata.net",
                          'http://sit.cloud.tapdata.net']:
            self._api = api_joint(TM, API)
            self.server = api_joint(self.serve, self._api).replace('/tm/', '/console/tm/')
        else:
            self._api = API
            self.server = api_joint(self.serve, self._api)

    def tapclient(self, method, url, **kwargs):
        COUNT = 0
        while True:
            try:
                response = self.session.request(method, url, **kwargs)
                return response.json()
            except Exception as e:
                logger.warning(e)
                logger.fatal('requests error')
                COUNT += 1
                if COUNT == requests_retime:
                    self.ERROR = True
                    return
                sleep(1)
                continue

    def daas_login(self):
        try:
            response = self.tapclient('GET', api_joint(self.serve, API, TIMESTAMP))
            stime = response['data']
            email = self.setting['email']
            password = self.setting['password']
            raw_sign = api_joint(email, password, stime, 'Gotapd8', division='')
            sign = tapsha1(raw_sign)
            login_data = {
                'email': email,
                'password': password,
                'stime': stime,
                'sign': sign
            }
            # 登录验证
            response2 = self.tapclient("POST", api_joint(self.serve, API, USERS, USERS_LOGIN), data=login_data)
            if self.ERROR is True:
                return
            # 更新headers中的信息
            access_id = response2['data']['id']
            userId = response2['data']["userId"]
            self.access_token = "?" + api_joint('access_token', access_id, division="=")
            # session中更新access_token
            self.session.headers.update({'Authorization': access_id})
            # # session中更新token
            self.session.cookies.update(
                {"user_id": userId, "isAdmin": '0', "token": access_id})
            self.user_id = userId
            self.cookies = self.session.cookies.items()
        except Exception as e:
            raise LoginFailedError

    def daas_ws(self):
        # 切割http地址
        ws = self.serve[7:]
        # 构造ws uri
        ws = api_joint("ws://", ws, "/ws/agent", self.access_token, division="")
        self.ws_uri = ws

    def dfs_login(self):
        ...

    def dfs_ws(self):
        ...

    def production_dfs_login(self):
        ...

    def production_dfs_ws(self):
        ...

    @staticmethod
    def dfs_path_transform(url):
        """
        云版企业版请求路径的变化
        :param url:
        :return:
        """
        _url = url.replace("tm", "console/tm")
        return _url

    # 条件筛选
    @staticmethod
    def filter(p):
        return '?filter=' + p

    # 条件筛选
    @staticmethod
    def where(p):
        return '?where=' + p

    # 条件筛选
    @staticmethod
    def name(p):
        return '?name=' + p


if __name__ == '__main__':
    i = V1ApiBase()
    logger.info(i.ws_uri)
